package com.gjp.learnjpa.controller;

import com.gjp.learnjpa.entity.Result;
import com.gjp.learnjpa.entity.User;
import com.gjp.learnjpa.repository.UserRepository;
import com.gjp.learnjpa.utils.ResultUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.validation.Valid;

/**
 * Created by Gjp on 2018/7/25.
 */
@RestController
public class UserController {

	@Autowired
	UserRepository userRepository;

	@GetMapping("/save")
	public Result<User> addUser(@Valid User user, BindingResult bindingResult){
		if (bindingResult.hasErrors()){
			return ResultUtil.error(400,bindingResult.getFieldError().getDefaultMessage());
		}
		return ResultUtil.success(userRepository.save(user));
	}

	@Transactional(rollbackFor = Exception.class)
	@GetMapping("/delete")
	public String delUser(User user) {
		userRepository.delete(user);
		return "ok";
	}

}
